import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_yres/model/vip_shoplist_model.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'vip_detail_page.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../pages/event/VipEven.dart';
// import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';

class VipShopPage extends StatefulWidget {
  String group_id;
  VipShopPage({Key key, this.group_id}) : super(key: key);

  @override
  _VipShopPageState createState() => _VipShopPageState(group_id);
}

class _VipShopPageState extends State<VipShopPage> {
  String group_id;
  _VipShopPageState(this.group_id);
  List<VipShopListModelData> shopData = []; //商品数组
  EasyRefreshController _controller = new EasyRefreshController();
  VipShopListModelData currentModel;
  // var min_id = 1; //分页
  int page = 1;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text('购买商品',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
        // actions: <Widget>[
        //   GestureDetector(
        //     child: Image.asset("images/icon_nav_share.png"),
        //   )
        // ],
      ),
      body: Container(
        height: MediaQuery.of(context).size.height -
            kToolbarHeight -
            ScreenUtil.getInstance().setHeight(DP_60) -
            MediaQueryData.fromWindow(window).padding.top,
        color: f0Color,
        child: new EasyRefresh(
          controller: _controller,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          child: GridView.builder(
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 0.0,
                crossAxisSpacing: 0.0,
                childAspectRatio: 0.69),
            itemBuilder: (context, index) {
              return getItemContainer(context, index);
            },
            itemCount: shopData == null ? 0 : shopData.length,
          ),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  //商品cell
  getItemContainer(BuildContext context, int index) {
    VipShopListModelData model = shopData[index];
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: model.price,
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30))),
        // TextSpan(
        //   text: model.itemprice,
        //   style: TextStyle(
        //       fontSize: 12.0,
        //       color: Colors.grey,
        //       decoration: TextDecoration.lineThrough,
        //       decorationColor: Colors.grey),
        // ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );

    return GestureDetector(
      child: Container(
          color: Colors.white,
          margin: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setWidth(5),
              0,
              ScreenUtil.getInstance().setWidth(5),
              ScreenUtil.getInstance().setWidth(5)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              CachedNetworkImage(
                width: (ScreenUtil.getInstance().setWidth(750) -
                        ScreenUtil.getInstance().setWidth(20)) /
                    2,
                height: (ScreenUtil.getInstance().setWidth(750) -
                        ScreenUtil.getInstance().setWidth(20)) /
                    2,
                fit: BoxFit.fill,
                imageUrl: Api.BaseUrl + model.img,
                placeholder: (context, url) => Image.asset(
                  'images/pic_default.png',
                  width: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                  height: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                  fit: BoxFit.fill,
                ),
                errorWidget: (context, url, error) => Image.asset(
                  'images/pic_default.png',
                  width: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                  height: (ScreenUtil.getInstance().setWidth(750) -
                          ScreenUtil.getInstance().setWidth(20)) /
                      2,
                  fit: BoxFit.fill,
                ),
              ),
              Container(
                  margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(8)),
                  child: Text(model.goods_name,
                      maxLines: 2,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(26)))),
              Row(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      margin:
                          EdgeInsets.all(ScreenUtil.getInstance().setWidth(8)),
                      child: price,
                    ),
                  ),
                  Expanded(
                      child: Container(
                    margin:
                        EdgeInsets.all(ScreenUtil.getInstance().setWidth(8)),
                    alignment: Alignment.bottomRight,
                    child: Text('',
                        style: TextStyle(fontSize: 11.0, color: Colors.grey)),
                  )),
                ],
              ),
            ],
          )),
      onTap: () {
        // print(model.itemid);
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (_) {
              return new NetLoadingDialog(
                loadingText: "跳转中...",
                bgColor: Color.fromARGB(255, 0, 0, 0),
                requestCallBack: null,
                outsideDismiss: false,
              );
            });
        currentModel = model;
        setState(() {});
        getString(TOKEN).then((value) {
          isOrder(value);
        });
      },
    );
  }

  //、是否正在处理订单
  isOrder(String token) async {
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response = await HttpUtil()
        .post(Api.BaseUrl + '/app.php?c=UserOrder&a=is_treating', data: data);
    Map userMap = json.decode(response.data);
    Navigator.of(context).pop(1);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      if (userMap['data']['is_treating'] == 'N') {
        Navigator.push(
            context,
            MaterialPageRoute(
                //导航打开新视图
                builder: (context) => VipShopDetailPage(
                    vipmodel: currentModel) //打开第二个页面，并传值，传递值的名称是model
                ));
      } else {
        Fluttertoast.showToast(msg: '订单处理中...');
      }
    }
  }

  loadList() async {
    FormData data =
        new FormData.fromMap({'group_id': group_id, 'p': page, 'per': '10'});
    Response<String> response =
        await HttpUtil().post(Api.VipShopListUrl, data: data);
    Map userMap = json.decode(response.data);
    VipShopListModelEntity itemEntity =
        new VipShopListModelEntity.fromJson(userMap);
    print('会员商品');
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    print(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (page == 1) {
            shopData.clear();
            shopData = itemEntity.data;
            _controller.finishRefresh();
          } else {
            shopData.addAll(itemEntity.data);
            _controller.finishLoad();
          }
        });
      }
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadList();

    APPLIC.eventBus.on<VipEven>().listen((event) {
      getString(TOKEN).then((value) {
        _getUserMsg(value);
      });
    });
  }

  //获取用户信息
  void _getUserMsg(token) async {
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetUserMsgUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1) {
      if (mounted) {
        setState(() {
          APPLIC.userInfoMap = userMap['data'];
          group_id = userMap['data']['user_msg']['group_id'];
          page = 1;
          loadList();
        });
      }
    }
    //  else{
    //     Fluttertoast.showToast(msg: userMap['msg']);
    //     Navigator.of(context).pushNamed("login");
    //     userMap = null;
    // }
  }
}
